from django.shortcuts import render
from django.views.generic import ListView,CreateView,UpdateView,DeleteView
from .models import Grade
from django.db.models import Q

from .forms import GradeForm
from django.urls import reverse_lazy


# Create your views here.
class GradeListView(ListView):
    model = Grade 
    template_name = "grades/grades_list.html"  # Specify your template name
    fields = ["grade_name", "grade_number"]  # Fields to display in the list view
    context_object_name = "grades"  # Name of the context variable to use in the template
    paginate_by = 10

    def get_queryset(self):
        queryset = super().get_queryset()
        search = self.request.GET.get("search")
        if search:
            queryset = queryset.filter(
                Q(grade_name__icontains=search) | Q(grade_number__icontains=search)
            )
        return queryset
    
    def get_context_data(self):
        context = super().get_context_data()
        # 获取所有班级并添加到上下文
        context['grades'] = Grade.objects.all().order_by('grade_number')  # 根据班级来排序
        context['current_grade'] = self.request.GET.get('grade', '') # int(self.request.GET.get('grade', 0))
        # context['search'] = self.request.GET.get('search', '')  
        return context
    

class GradeCreateView(CreateView):
    model = Grade
    template_name = 'grades/grade_form.html'
    form_class = GradeForm  # Assuming you have a form class defined for Grade 
    success_url = reverse_lazy('grades_list')  # 返回成功后应重定向到的URL

 
class GradeUpdateView(UpdateView):
    model = Grade
    template_name = 'grades/grade_form.html'
    form_class = GradeForm  # Assuming you have a form class defined for Grade 
    success_url = reverse_lazy('grades_list')  # 返回成功后应重定向到的URL

class GradeDeleteView(DeleteView):
    model = Grade
    template_name = 'grades/grade_delete_confirm.html'  # Template for confirmation
    success_url = reverse_lazy('grades_list')  # Redirect after deletion